import { saveArticle,fetchLatestApi,displayArticle} from '../services/articles';
import {message} from 'antd'
import {routerRedux} from 'dva/router'

//models里面的处理流程
export default{
  namespace:'articles',
  state:{
    // isSavedSuccess:false
    latest:[],
    entities: {},
    // currentArticle:[]
  },
  effects:{
    *addArticles({payload},{call,put}){
      yield call(saveArticle,payload)  //调用其他函数的函数    发送请求是用saveArticle函数
      message.success('保存成功！')
      yield put(routerRedux.push('/articles/latest'))
    },
    *fetchLatest(_,{call,put}){
      const resp = yield call(fetchLatestApi)
      yield put({
        type:'setLatest',
        payload:resp,
      })
    },
    *fetchArticleById({articleId},{call,put}){
      const resp = yield call(displayArticle,articleId)
      yield put({
        type:'setShow',
        payload:resp,
      })
    },
  },
  //收到一些要修改的action要怎么办
  reducers:{
    //接收两个参数：当前state的值和action，然后基于action的type决定如何处理state
    //表示一个属性   直接返回一个对象   reduce(acc,value)  value:当前的值，初始值；acc：是一个函数 ；
    // setSuccessFlag:state => ({...state,isSavedSuccess:true})
    setLatest(state,action){
      const newEntities = action.payload.reduce((acc,art) => {
        acc[art.id] = art
        return acc
      },{})
      return {
        ...state,//表示把原来的全部取过来
        latest: action.payload,
        entities:{
          ...state.entities,
          ...newEntities
        }
      }
    },
    setShow(state,action){
      return {
        ...state,//表示把原来的全部取过来
        // currentArticle: action.articleId,
        entities:{
          ...state.entities,
          [action.payload.id]: action.payload
        }
      }
    },
  },
}
